#!/usr/bin/php -d mysqlnd.net_read_timeout=3600
<?php
set_include_path("../../../include");
require("header.inc.php");

$startShard = !empty($argv[1]) ? $argv[1] : 1;

$shardIDs = Zotero_DB::columnQuery("SELECT shardID FROM shards WHERE shardID >= ? ORDER BY shardID", $startShard);
foreach ($shardIDs as $shardID) {
	echo "Shard: $shardID\n";
	
	Zotero_DB::query("INSERT IGNORE INTO itemTopLevel SELECT itemID, sourceItemID FROM itemAttachments WHERE sourceItemID IS NOT NULL UNION SELECT itemID, sourceItemID FROM itemNotes WHERE sourceItemID IS NOT NULL", false, $shardID);
	Zotero_DB::query("DELETE ITL FROM itemTopLevel ITL LEFT JOIN (SELECT itemID, sourceItemID FROM itemAttachments UNION SELECT itemID, sourceItemID FROM itemNotes) S ON (ITL.itemID=S.itemID AND ITL.topLevelItemID=S.sourceItemID) WHERE S.itemID IS NULL", false, $shardID);
}
